package session;

import entity.Category;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.ejb.Stateless;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Gestisce le interazioni con il Web Service di e-bay.
 *
 * @author Rachid Ouchary, Fabio Strocco, Max Passaghe, Marco Tansini.
 */
@Stateless
public class EbayRequestHandler implements EbayRequestHandlerRemote {

    //@EJB
    //private CategoryFacade categoryFacade;
    public final String border = "0", width = "80", height = "80";
//Long categoria

    public String request(Category c, String descrizione) {
        //Category c = categoryFacade.find(categoria);
        String results = "";
        InputStream in = null;
        Document doc = null;

        try {
            String url = generaURL(c.getEbayID(), descrizione);
            System.out.println(url);
            URL xmlUrl = new URL(url);
            in = xmlUrl.openStream();
            doc = parse(in);
            if (doc == null) {
                url = generaURLOnlyKeywords(descrizione);
                in = xmlUrl.openStream();
                doc = parse(in);
                System.out.println("uso solo keywords, url " + url);
            }

            // normalize text representation
            doc.getDocumentElement().normalize();
            String ack = doc.getElementsByTagName("ack").item(0).getChildNodes().item(0).getNodeValue();
            System.out.println(ack);
            if (ack.equals("Failure")) {
                url = generaURLOnlyKeywords(descrizione);
                xmlUrl = new URL(url);
                in = xmlUrl.openStream();
                doc = parse(in);
                System.out.println("uso solo keywords, url " + url);
                doc.getDocumentElement().normalize();
            }

        } catch (IOException ex) {
            results += "<error>Errore nella parsificazione della risposta da ebay</error>";
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                results += "<error>Errore in chiusura dello stream</error>";
            }
        }

        results = parse(doc, descrizione);


        return results;
    }

    /**
     * Constructs a Document object by reading from an input stream.
     */
    private static Document parse(InputStream is) {
        Document ret = null;
        DocumentBuilderFactory domFactory;
        DocumentBuilder builder;

        try {
            domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setValidating(false);
            domFactory.setNamespaceAware(false);
            builder = domFactory.newDocumentBuilder();
            ret = builder.parse(is);
        } catch (Exception ex) {
            System.err.println("unable to load XML: " + ex);
        }
        return ret;
    }

    private String generaURL(String categoria, String descrizione) {
        String url = "";
        String appID = "uni431a3c-f004-41de-89c9-4847a52d15f";


        url += "http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsAdvanced"
                + "&SERVICE-VERSION=1.0.0"
                + "&SECURITY-APPNAME=" + appID
                + "&RESPONSE-DATA-FORMAT=XML"
                + "&REST-PAYLOAD"
                + "&itemFilter(0).name=Condition"
                + "&itemFilter(0).value=New"
                + "&itemFilter(1).name=ListingType"
                + "&itemFilter(1).value(0)=FixedPrice"
                + "&itemFilter(1).value(1)=AuctionWithBIN"
                + "&itemFilter(1).value(2)=StoreInventory"
                + "&paginationInput.entriesPerPage=5"
                + "&categoryId=" + categoria
                + "&keywords=" + descrizione.replaceAll(" ", "%20")
                + "&descriptionSearch=true";

        return url;
    }

    private String parse(Document doc, String description) {
        String result = "";
        NodeList items = doc.getElementsByTagName("item");
        String title = "", imageURL = "", currentPrice = "", itemURL = "", timeLeft = "";
        Node nodo = null;
        CharacterData dato;
        NodeList figli;

        for (int i = 0; i < items.getLength(); i++) {
            Node item = items.item(i);
            figli = item.getChildNodes();

            for (int k = 0; k < figli.getLength(); k++) {
                Node figlio = figli.item(k);
                String nodeName = figlio.getNodeName();
                //System.out.println("node= " + nodeName);

                if (nodeName.equals("title")) {
                    dato = (CharacterData) figlio.getFirstChild();
                    title = dato.getData();
                    //System.out.println("title= " + title);
                } else if (nodeName.equals("galleryURL")) {
                    dato = (CharacterData) figlio.getFirstChild();
                    imageURL = dato.getData();
                    //System.out.println("imageURL= " + imageURL);
                } else if (nodeName.equals("viewItemURL")) {
                    dato = (CharacterData) figlio.getFirstChild();
                    itemURL = dato.getData();
                    //System.out.println("itemURL= " + itemURL);
                } else if (nodeName.equals("sellingStatus")) {

                    currentPrice = figlio.getFirstChild().getFirstChild().getNodeValue();
                    //System.out.println("currentPrice= " + currentPrice);
                } else if (nodeName.equals("TimeLeft")) {
                    dato = (CharacterData) figlio.getFirstChild();
                    timeLeft = dato.getData();
                    //System.out.println("timeLeft= " + timeLeft);
                }
            }

            result += "<div id=\"item\">"
                    + "<div id=\"title\">"
                    + title
                    + "</div>"
                    + "<div id=\"galleryURL\">"
                    + "<img src=\""
                    + imageURL
                    + "border=\""
                    + border
                    + "\" width=\""
                    + width
                    + "\" height=\""
                    + height
                    + "\">"
                    + "</div>"
                    + "<div id=\"viewItemURL\">"
                    + "<a target='_blank' href=\""
                    + itemURL
                    + "\">ItemLink</a>"
                    + "</div>"
                    + "<div id=\"CurrentPrice\">"
                    + currentPrice + "$"
                    + "</div>"
                    + "<div id=\"TimeLeft\">"
                    + timeLeft
                    + "</div>"
                    + "</div>";

        }
        if(result.equals("")) result+="Spiacenti, non sono stati trovati risultati, Prova a cercare su ebay";
        return result+ "<div id=\"LinkToEbay\">"
                    + "<form method=\"get\" action=\"http://search.ebay.com/search/search.dll\">"
                    + "<input type=\"hidden\" name=\"satitle\" id=\"satitle\" value=\""
                    + description.replaceAll("%20", " ")
                    + "\"/>"
                    + "<input type=\"submit\" value=\"Cerca su eBay!\">"
                    + "</form>"
                    + "</div>";
    }

    private String generaURLOnlyKeywords(String descrizione) {
        String url = "";
        String appID = "uni431a3c-f004-41de-89c9-4847a52d15f";


        url += "http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords"
                + "&SERVICE-VERSION=1.0.0"
                + "&SECURITY-APPNAME=" + appID
                + "&RESPONSE-DATA-FORMAT=XML"
                + "&REST-PAYLOAD"
                + "&itemFilter(0).name=Condition"
                + "&itemFilter(0).value=New"
                + "&itemFilter(1).name=ListingType"
                + "&itemFilter(1).value(0)=FixedPrice"
                + "&itemFilter(1).value(1)=AuctionWithBIN"
                + "&itemFilter(1).value(2)=StoreInventory"
                + "&paginationInput.entriesPerPage=5"
                + "&keywords=" + descrizione.replaceAll(" ", "%20")
                + "&descriptionSearch=true";

        return url;
    }
}
